package tx.bj12320.facade;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.logging.Logger;

import javax.jws.WebService;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.org.rapid_framework.page.Page;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;

import tx.bj12320.model.DataDict;
import tx.bj12320.model.OrgInfo;
import tx.bj12320.model.TszbProcessInfo;
import tx.bj12320.model.UserInfo;
import tx.bj12320.model.enums.DdTypeEnum;
import tx.bj12320.model.enums.WorkOrderTypeEnum;
import tx.bj12320.service.DataDictManager;
import tx.bj12320.service.OrgInfoManager;
import tx.bj12320.service.TszbProcessInfoManager;
import tx.bj12320.service.UserInfoManager;
import tx.bj12320.vo.query.DataDictQuery;
import tx.bj12320.vo.query.TszbProcessInfoQuery;
import tx.bj12320.vo.query.TszbProcessInfoQueryFacade;

@Service
@Transactional
@WebService(endpointInterface = "tx.bj12320.facade.TszbFacade")
public class TszbFacadeImpl implements TszbFacade {
	private static Logger log = Logger.getLogger(TszbFacadeImpl.class.getName());
	@Autowired
	private TszbProcessInfoManager tszbProcessInfoManager;
	public void setTszbProcessInfoManager(TszbProcessInfoManager manager) {
		this.tszbProcessInfoManager = manager;
	}
	@Autowired
	private OrgInfoManager orgInfoManager;
	public void setOrgInfoManager(OrgInfoManager manager) {
		this.orgInfoManager = manager;
	}
	@Autowired
	private DataDictManager dataDictManager;
	public void setDataDictManager(DataDictManager manager) {
		this.dataDictManager = manager;
	}
	@Autowired
	private UserInfoManager userInfoManager;
	public void setUserInfoManager(UserInfoManager manager) {
		this.userInfoManager = manager;
	}
	@Override
	public int createTszbProcess(String xml) {
		log.info(xml);

		XStream x=new XStream(new StaxDriver());
		x.alias("TszbProcessInfoQuery", TszbProcessInfoQueryFacade.class);

//		x.omitField(TszbProcessInfoQuery.class, "ticketId");

		TszbProcessInfoQueryFacade qf=(TszbProcessInfoQueryFacade)x.fromXML(xml);

		TszbProcessInfo tszbProcessInfo=new TszbProcessInfo();

		tszbProcessInfo.setCcTicketid(qf.getTicketId());
		tszbProcessInfo.setCcCreateuserid(qf.getCreateUserId());
		tszbProcessInfo.setCcWorkfflowid(qf.getWorkfFlowId());
		tszbProcessInfo.setCcXml(xml);

		tszbProcessInfo.setCallerName(qf.getCustomerName());
		tszbProcessInfo.setCallerNumber(qf.getCallNo());
		tszbProcessInfo.setAge(qf.getCustomerAge());
		tszbProcessInfo.setSex(qf.getCustomerSex());
		tszbProcessInfo.setEduDegreee(qf.getCustomerEduLever());
		tszbProcessInfo.setCellPhone(qf.getCustomerTel());
		tszbProcessInfo.setOccupation(qf.getCustomerJob());
		tszbProcessInfo.setContaceAddress(qf.getCustomerAddress());
		tszbProcessInfo.setPhone(qf.getContactorPhone());
		tszbProcessInfo.setArea(qf.getCustomerArea());
		tszbProcessInfo.setShouliTime(new java.util.Date());
		String cuserid=tszbProcessInfo.getCcCreateuserid();
		UserInfo ui=userInfoManager.getByUserCode(cuserid);
		if(ui!=null){
			tszbProcessInfo.setShoulliPerson(ui.getRealName()+"("+ui.getAgentDn()+")");
		}

		if(qf.getWorkfFlowId().equals("adviseworkflow")){//建议受理单
			tszbProcessInfo.setWorkOrderType(WorkOrderTypeEnum.JYSLD.getCode());
			tszbProcessInfo.setIncomingCallContent(qf.getAdviceContent());
			tszbProcessInfo.setZoneName(qf.getAdviceCompanyArea());

			//对应网络单位
			parseUnitInfo(qf.getAdviceCompany(), tszbProcessInfo);

			//对应每种工单的具体类型（建议分类）（工单分类）
			parseWorkOrderSort(qf.getAdviceType(), tszbProcessInfo);

			//对应工单来源
			parseWorkOrderSource(qf.getAdviceAcceptType(), tszbProcessInfo);

		}else if(qf.getWorkfFlowId().equals("praiseworkflow")){//表扬受理单
			tszbProcessInfo.setWorkOrderType(WorkOrderTypeEnum.BYSLD.getCode());
			tszbProcessInfo.setIncomingCallContent(qf.getPraiseContent());
			tszbProcessInfo.setZoneName(qf.getPraiseCompanyArea());

			//对应网络单位
			parseUnitInfo(qf.getPraiseCompany(), tszbProcessInfo);

			//对应每种工单的具体类型（建议分类）（工单分类）
			parseWorkOrderSort(qf.getPraiseType(), tszbProcessInfo);

			//对应工单来源
			parseWorkOrderSource(qf.getPraiseAcceptTpye(), tszbProcessInfo);

		}else if(qf.getWorkfFlowId().equals("appealworkflow")){//投诉协调单
			tszbProcessInfo.setIncomingCallContent(qf.getAppealContent());
			tszbProcessInfo.setZoneName(qf.getAppealCompanyArea());
			if(qf.getIsTicket().equals("1")){//形成工单
				tszbProcessInfo.setWorkOrderType(WorkOrderTypeEnum.TSXTD.getCode());
			}else if (qf.getIsTicket().equals("0")){//不形成工单
				tszbProcessInfo.setWorkOrderType(WorkOrderTypeEnum.TSWXCGZD.getCode());
				tszbProcessInfo.setResolveWay(qf.getNoSheetReason());
			}

			//对应网络单位
			parseUnitInfo(qf.getAppealCompany(), tszbProcessInfo);

			//对应每种工单的具体类型（建议分类）（工单分类）
			parseWorkOrderSort(qf.getAppealTypeName(), tszbProcessInfo);

			//对应工单来源
			parseWorkOrderSource(qf.getAcceptType(), tszbProcessInfo);

		}else if(qf.getWorkfFlowId().equals("impeachworkflow")){//举报受理单
			tszbProcessInfo.setWorkOrderType(WorkOrderTypeEnum.JBSLD.getCode());
			tszbProcessInfo.setIncomingCallContent(qf.getImpeachContent());
			tszbProcessInfo.setZoneName(qf.getImpeachArea());
			tszbProcessInfo.setEventName(qf.getImpeachName());

			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			try {
				tszbProcessInfo.setHappenTime(sdf.parse((qf.getHappenTime())));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
//			tszbProcessInfo.setHappenTime(Date.valueOf(qf.getHappenTime()));

			tszbProcessInfo.setDetailAddress(qf.getHappenPlace());
			tszbProcessInfo.setAffectPersonCount(qf.getImpeachPerson());
			tszbProcessInfo.setInvasionPersonCount(qf.getApprovePerson());
			tszbProcessInfo.setDeathPersonCount(qf.getDiedPerson());

			//对应网络单位
//			parseUnitInfo(qf.getPraiseCompany(), tszbProcessInfo);
			tszbProcessInfo.setOrgInfoId(1L);//举报受理单呼叫中心不选择网络单位

			//对应每种工单的具体类型（建议分类）（工单分类）
			parseWorkOrderSort(qf.getPraiseType(), tszbProcessInfo);

			//对应工单来源
			parseWorkOrderSource(qf.getImpeachAcceptType(), tszbProcessInfo);

		}else{
			log.info("<workfFlowId></ workfFlowId >//工单类型， 无法找到对应的工单类型！："+qf.getWorkfFlowId());
			return 0;
		}

		tszbProcessInfoManager.startProcess(tszbProcessInfo);

		if(xml.length()==0){
			return 0;
		}else{
			return 1;
		}

	}
	/**
	 * 对应每种工单的具体类型（建议分类）（工单分类）
	 * @param workOrderSortDdValue   呼叫中心xml中的值
	 * @param tszbProcessInfo
	 */
	private void parseWorkOrderSort(String workOrderSortDdValue,
			TszbProcessInfo tszbProcessInfo) {
//		log.info(workOrderSortDdValue);
		if(workOrderSortDdValue==null||workOrderSortDdValue.length()==0) return;
		tszbProcessInfo.setWorkOrderSortDdValue(workOrderSortDdValue);
		DataDictQuery query=new DataDictQuery();
		query.setDdType(DdTypeEnum.TSZB__WORK_ORDER_SORT_JYFL.getCode());
		query.setDdCode(workOrderSortDdValue);
		Page page =dataDictManager.findPage(query);
		if(page.getResult()!=null){
			List l=page.getResult();
			if(l.size()>0){
				tszbProcessInfo.setWorkOrderSort(((DataDict)l.get(0)).getDdName());
			}else{
				tszbProcessInfo.setWorkOrderSort(workOrderSortDdValue);
			}
		}
	}
	/**
	 * 对应工单来源
	 * @param workOrderSortDdValue
	 * @param tszbProcessInfo
	 */
	private void parseWorkOrderSource(String workOrderSourceDdValue,
			TszbProcessInfo tszbProcessInfo) {
		tszbProcessInfo.setWorkOrderSourceDdValue(workOrderSourceDdValue);
		DataDictQuery query=new DataDictQuery();
		query.setDdType(DdTypeEnum.TSZB__WORK_ORDER_SOURCE.getCode());
		query.setDdCode(workOrderSourceDdValue);
		query.setPageSize(1);
		Page page =dataDictManager.findPage(query);
		if(page.getResult()!=null){
			List l=page.getResult();
			if(l.size()>0){
				tszbProcessInfo.setWorkOrderSource(((DataDict)l.get(0)).getDdName());
			}else{
				tszbProcessInfo.setWorkOrderSource(workOrderSourceDdValue);
			}
		}
	}
	/**
	 * 对应网络单位
	 * @param unitCode 呼叫中心xml中的值
	 * @param tszbProcessInfo
	 */
	private void parseUnitInfo(String unitCode,
			TszbProcessInfo tszbProcessInfo) {
		OrgInfo oi=orgInfoManager.getByOrgCode(unitCode);
		if(oi!=null){
			tszbProcessInfo.setOrgInfoId(oi.getOrgInfoId());
			tszbProcessInfo.setRelaUnitName(oi.getOrgName());
		}else{
			log.info("无法找到对应的网络单位!："+unitCode);
		}

		tszbProcessInfo.setRelaUnitCode(unitCode);
	}

	private void xstreamTest(){
		XStream x=new XStream();
		TszbProcessInfoQuery q=new TszbProcessInfoQuery();
		q.setAffectPersonCount("10personcount");
		q.setCallerName("张三");
		try {
			x.toXML(q, new FileOutputStream("E:\\work_files\\readworks\\bj12320_project\\test.xml"));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void jaxbTest(){
		try {
			JAXBContext ctx=JAXBContext.newInstance("tx.bj12320.vo.query",TszbProcessInfoQuery.class.getClassLoader());
			Marshaller m=ctx.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			TszbProcessInfoQuery q=new TszbProcessInfoQuery();
			q.setAffectPersonCount("10personcount");
			q.setCallerName("张三");
			try {
				m.marshal(q, new FileOutputStream("E:\\work_files\\readworks\\bj12320_project\\test.xml"));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} catch (JAXBException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
